package com.clayecloud.module_main.ui.fragment;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.clayecloud.lib_base.action.ToastAction;
import com.clayecloud.lib_base.adapter.BaseDialog;
import com.clayecloud.lib_base.dialog.MenuDialog;
import com.clayecloud.lib_common.room.ClientDataBase;
import com.clayecloud.lib_common.room.entity.ClientBase;
import com.clayecloud.lib_common.utils.LoginUtil;
import com.clayecloud.module_main.R;
import com.clayecloud.module_main.adapter.HomeViewDatabindingAdapter;

import com.clayecloud.module_main.databinding.FragmentHomeBinding;
import com.clayecloud.module_main.entity.TitleText;
import com.clayecloud.module_main.viewModels.FragmentHomeViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.OnTitleBarListener;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.transformers.Transformer;


import java.util.ArrayList;
import java.util.List;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;


public class HomeFragment extends Fragment implements ToastAction {

    // 实现“onRequestPermissionsResult”函数接收校验权限结果。
    private final int PERMISSIONS_LENGTH = 2;
    // 相机权限码
    private final int CAMERA_REQ_CODE = 111;
    //scan回调校验码
    private final int REQUEST_CODE_SCAN_ONE =112;
    private FragmentHomeBinding fragmentHomeBinding;
    private FragmentHomeViewModel fragmentHomeViewModel;

    /**
     * 处理HomeFragment中的页面刷新监听等
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragmentHomeBinding= DataBindingUtil.inflate(inflater, R.layout.fragment_home,container,false);
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        fragmentHomeViewModel = viewModelProvider.get(FragmentHomeViewModel.class);
        init();
        initListener();
        return fragmentHomeBinding.getRoot();
    }

    /**
     * 初始化函数
     */
    private void init() {
        //初始化数据
        fragmentHomeViewModel.loadData();
        fragmentHomeBinding.setViewModel(fragmentHomeViewModel);
        //设置AppBarLayout的高程（原始的设置方式已经被弃用）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StateListAnimator stateListAnimator = new StateListAnimator();
            stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(fragmentHomeBinding.appBarLayout, "elevation", 0.1f));
            fragmentHomeBinding.appBarLayout.setStateListAnimator(stateListAnimator);
        }
        //轮播图  需要改成从网络端获取的 所有数据 在 fragmentHomeViewModel 中进行获取
        List<String> list = new ArrayList<>();
        list.add("https://aecpm.alicdn.com/simba/img/TB15tIjGVXXXXcoapXXSutbFXXX.jpg");
        list.add("https://aecpm.alicdn.com/simba/img/TB1CWf9KpXXXXbuXpXXSutbFXXX.jpg_q50.jpg");
        list.add("https://picasso.alicdn.com/imgextra/i3/344103/O1CNA1g1ffNQ100d6c9ec66e0b0b76530002_!!344103-0-picassobanner.jpg");
        list.add("https://gw.alicdn.com/imgextra/i3/75/O1CN011kYrp81CQOJHwJ8uu_!!75-0-lubanu.jpg");
        list.add("https://gw.alicdn.com/imgextra/i4/32/O1CN01AVa4Sr1C6hHPJfnPK_!!32-0-lubanu.jpg");
        fragmentHomeBinding.banner.setData(list,null);
        fragmentHomeBinding.banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                //设置图片圆角角度
                RoundedCorners roundedCorners = new RoundedCorners(25);
                //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
                RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                Glide.with(getActivity()).load(list.get(position)).apply(options).into((ImageView) view);
            }
        });
        fragmentHomeBinding.banner.setPageTransformer(Transformer.Default);

        //多彩资讯
        fragmentHomeBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        HomeViewDatabindingAdapter homeViewDatabindingAdapter = new HomeViewDatabindingAdapter(getContext(),fragmentHomeViewModel.getNewsList().getValue());
        fragmentHomeBinding.recyclerView.setAdapter(homeViewDatabindingAdapter);
    }

    /**
     * 对事件进行监听
     */
    private void initListener() {
        // 滑动监听
        fragmentHomeBinding.nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            @SuppressLint("ResourceAsColor")
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // 上滑改变透明度的变化
                if (scrollY <= 230){
                    fragmentHomeBinding.titleBarFrame.setBackgroundColor(Color.argb(scrollY,255,255,255));
                }
            }
        });
        //TiteBar点击事件监听
        fragmentHomeBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View view) {
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==0) {
                    ARouter.getInstance()
                            .build("/login/account/index")
                            .withTransition(R.anim.window_bottom_in, R.anim.window_fake)
                            .navigation(fragmentHomeBinding.getRoot().getContext());
                    return;
                }
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {
                scan();
            }
        });
        //对用户状态的判断
        ClientDataBase.getClientDataBaseInstance().getClientBaseService().getClientBaseById(1).observe(this, new Observer<ClientBase>() {
            @Override
            public void onChanged(ClientBase clientBase) {
                if(clientBase == null){
                    fragmentHomeViewModel.setIslogin(false);
                    return;
                }
                if(clientBase.getUserID() == 0){
                    fragmentHomeViewModel.setIslogin(false);
                    fragmentHomeViewModel.noLoginTitle();
                    ARouter.getInstance()
                            .build("/login/account/index")
                            .withTransition(R.anim.window_bottom_in, R.anim.window_fake)
                            .navigation(fragmentHomeBinding.getRoot().getContext());
                }else{
                    fragmentHomeViewModel.setIslogin(true);
                    fragmentHomeViewModel.authenticationLoginState(clientBase.getUserID());
                }
            }
        });
        //针对自定义无法刷新自己监听刷新
        fragmentHomeViewModel.getTextwIsChange().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                fragmentHomeBinding.titleBar.setLeftTitle(fragmentHomeViewModel.getTitleTextMutableLiveData().getValue().getStr_titlePrimaryText());
            }
        });
        //对处理结果进行监听
        fragmentHomeViewModel.getBool_relogin().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    toast("登录已过期，请从新登录");
                    fragmentHomeViewModel.noLoginTitle();
                    ARouter.getInstance()
                            .build("/login/account/index")
                            .withTransition(R.anim.window_bottom_in, R.anim.window_fake)
                            .navigation(fragmentHomeBinding.getRoot().getContext());
                    LoginUtil.userLoginOut();
                }else{
                    fragmentHomeBinding.titleBar.setLeftTitle(fragmentHomeViewModel.getTitleTextMutableLiveData().getValue().getStr_titlePrimaryText());
                }
            }
        });
        // 身份卡点击事件跳转
        fragmentHomeBinding.idCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                ARouter.getInstance()
                        .build("/idCard/index")
                        .withTransition(R.anim.window_right_in, R.anim.window_fake)
                        .navigation(fragmentHomeBinding.getRoot().getContext());
            }
        });
        // 物业缴费点击事件
        fragmentHomeBinding.propertyPayment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                ARouter.getInstance()
                        .build("/pay/index")
                        .withTransition(R.anim.window_right_in, R.anim.window_fake)
                        .navigation(fragmentHomeBinding.getRoot().getContext());
            }
        });
        // 访客邀请点击事件监听
        fragmentHomeBinding.visitor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                ARouter.getInstance()
                        .build("/visitor/index")
                        .withTransition(R.anim.window_right_in, R.anim.window_fake)
                        .navigation(fragmentHomeBinding.getRoot().getContext());
            }
        });
        //我的房屋点击事件监听
        fragmentHomeBinding.house.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                ARouter.getInstance()
                        .build("/house/index")
                        .withTransition(R.anim.window_right_in, R.anim.window_fake)
                        .navigation(fragmentHomeBinding.getRoot().getContext());
            }
        });
        //报事报修的点击事件监听
        fragmentHomeBinding.repair.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                ARouter.getInstance()
                        .build("/repair/index")
                        .withTransition(R.anim.window_right_in, R.anim.window_fake)
                        .navigation(fragmentHomeBinding.getRoot().getContext());
            }
        });
        // 投诉建议点击事件监听
        fragmentHomeBinding.suggestionsPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                if(fragmentHomeViewModel.getLeftHeaderButton()==1){
                    showBindHouse();
                    return;
                }
                toast("暂未开通此服务");
            }
        });


        // 服务电话点击事件
        fragmentHomeBinding.serviceTelephone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                List<String> data = new ArrayList<>();
                data.add("呼叫 400 400 1112");
                // 底部选择框
                new MenuDialog.Builder(getContext())
                        .setList(data)
                        .setListener(new MenuDialog.OnListener() {
                            @Override
                            public void onSelected(com.clayecloud.lib_base.dialog.BaseDialog dialog, int position, Object o) {
                                toast("位置：" + position + "，文本：" + o.toString());
                            }
                        })
                        .show();
            }
        });
        // 热线电话点击事件
        fragmentHomeBinding.hotline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fragmentHomeViewModel.getIslogin()){
                    toast("请先进行登录,登录后即可正常使用");
                    return;
                }
                List<String> data = new ArrayList<>();
                data.add("呼叫 400 400 1111");
                // 底部选择框
                new MenuDialog.Builder(getContext())
                        .setList(data)
                        .setListener(new MenuDialog.OnListener() {
                            @Override
                            public void onSelected(com.clayecloud.lib_base.dialog.BaseDialog dialog, int position, Object o) {
                                toast("位置：" + position + "，文本：" + o.toString());
                            }
                        })
                        .show();
            }
        });
    }

    /**
     *  提示绑定房屋，并跳转到绑定页面
     */
    public void showBindHouse(){
        new BaseDialog.Builder<>(getActivity())
                .setContentView(R.layout.dialog_bindinghouse)
                .setAnimStyle(BaseDialog.ANIM_IOS)
                .setOnClickListener(R.id.btn_dialog_custom_ok, (BaseDialog.OnClickListener<Button>) (dialog, button) -> {
                    ARouter.getInstance()
                            .build("/house/add/index")
                            .withTransition(R.anim.window_right_in, R.anim.window_fake)
                            .navigation(fragmentHomeBinding.getRoot().getContext());
                    dialog.dismiss();
                }).show();
    }

    /**
     * 用来处理创建除view的所有东西
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式状态栏
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    /**
     * 在删除此fragment时 进行操作防止内存泄漏
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        ImmersionBar.destroy(this);
    }

    /**
     * 进行动态的相机权限查询验证
     */
    public void scan(){
        // CAMERA_REQ_CODE为用户自定义，用于接收权限校验结果的请求码。
        this.requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_REQ_CODE);
    }

    /**
     * 进行动态的相机权限查询验证回调，成功后调用扫二维码
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 判断“requestCode”是否为申请权限时设置请求码CAMERA_REQ_CODE，然后校验权限开启状态。
        if (requestCode == CAMERA_REQ_CODE && grantResults.length == PERMISSIONS_LENGTH && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            // 调用扫码接口，构建扫码能力。
            HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE).create();
            ScanUtil.startScan(getActivity(), REQUEST_CODE_SCAN_ONE, options);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //刷新
        fragmentHomeViewModel.checkUserBindHouse(LoginUtil.getUserID());
    }
}
